﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;

namespace woaC2.SocketLib
{
    public sealed class ClientRegistry
    {
        #region Singletone

        private ClientRegistry()
        {
        }

        public static ClientRegistry instance
        {
            get
            {
                return Nested.instance;
            }
        }

        private class Nested
        {
            static Nested()
            {
            }
            internal static readonly ClientRegistry instance = new ClientRegistry();
        }

        #endregion

        /// <summary>
        /// Danh sách lưu trữ các client kết nối
        /// </summary>
        private readonly ConcurrentDictionary<Guid, Client> _clients = new ConcurrentDictionary<Guid, Client>();

        internal int Count
        {
            get
            {
                return this._clients.Count;
            }
        }

        internal void Add(Client client)
        {
            this._clients.TryAdd(client.SessionID, client);
        }

        internal bool Contains(Guid sessionId)
        {
            return this._clients.ContainsKey(sessionId);
        }

        public IList<Client> GetAll()
        {
            var list = this._clients.Select(pair => pair.Value).ToList();
            return list.AsReadOnly();
        }

        public Client GetById(Guid sessionId)
        {
            if (this._clients.ContainsKey(sessionId))
            {
                return this._clients[sessionId];
            }
            return null;
        }

        internal void Remove(Guid sessionId)
        {
            try
            {
                if (_clients.ContainsKey(sessionId))
                {
                    Client val;
                    _clients[sessionId].TcpClient.Client.Close();
                    _clients[sessionId].TcpClient.Client.Dispose();
                    _clients[sessionId].TcpClient.Close();
                    this._clients.TryRemove(sessionId,out val);
                }
            }
            catch(ArgumentNullException ex)
            {
                SocketLog.Write("[ClientRegistry.Remove]--[ERROR]--" + ex);
            }
        }
    }
}